package com.bayss.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.bayss.core.constant.ResultMsg;
import com.bayss.core.service.BakService;
import com.bayss.core.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户操作
 *
 * @author yangjian
 */
@Slf4j
@RestController
public class FileController extends ApiBaseController{
    private final BakService bakService;
    private OSS ossClient;

    @Autowired
    public FileController(BakService bakService){
        ossClient = new OSSClientBuilder().build("https://oss-cn-beijing.aliyuncs.com", "LTAI4FjvBA5HR1Yk4xf6AERV", "oKL3jHhk4pX4nL8rZrvHuNPSkyhC0C");
        this.bakService = bakService;
    }

    /**
     * 图片上传
     *
     * @return success
     */
    @RequestMapping("/upload.json")
    public ResultMsg upload(@RequestParam(name = "doko_file") MultipartFile file) throws Exception {
        String name = System.currentTimeMillis()+ DigestUtils.md5Hex(file.getOriginalFilename()).toUpperCase();
        name = "doko-web/"+ name;
        PutObjectRequest putObjectRequest = new PutObjectRequest("doko-way", name, file.getInputStream());
        ossClient.putObject(putObjectRequest);
        bakService.saveBak(name, "doko-web");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("key", name);
        jsonObject.put("url", FileUtil.imgUrl(name));
        return ResultMsg.success(jsonObject);
    }

}
